package fv;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import net.sf.json.JSONObject;
import net.sf.json.JSONArray;
import java.sql.*;
//import java.text.SimpleDateFormat;
//import java.util.Date;
import java.util.Iterator;
import java.util.List;

/**
 * Servlet implementation class outfits
 */
public class outfits extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	public JSONObject json = new JSONObject();
	JSONArray jsonArr = new JSONArray();
	int retcnt = 25;
	String userid = null;
	String outfitid = null;
	String share = null;
	int like = -1;
	String sqlstr = null;

	private File tmpDir;
	private static final String DESTINATION_DIR_PATH = "c:\\xzn\\files";

    /**
     * @see HttpServlet#HttpServlet()
     */
    public outfits() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		userid = request.getParameter("token");
		outfitid = request.getParameter("id");
		if (userid == null && outfitid == null)
		{
			sqlstr = "select * from photos where share = 1 order by photoid desc limit " + retcnt;
		}
		else if (userid == null && outfitid != null)
		{
			sqlstr = "select * from photos where photoid = " + outfitid;
		}
		else if (userid != null && outfitid == null)
		{
			sqlstr = "select photoid, photoname, emailaddr, likes, dislikes, share from photos, ferdict_user where owner = " + userid + " and userid = owner order by photoid desc limit " + retcnt;
		}
		
		Connection conn = mysqlconn.getConn();
		json.clear();
		try {
			Statement s = conn.createStatement();
			s.executeQuery(sqlstr);
			ResultSet rs = s.getResultSet();
			
			while (rs.next())
			{
				json.put("id", rs.getString(1));
				json.put("name", DESTINATION_DIR_PATH+"\\"+rs.getString(2)+".png");
				json.put("owner", rs.getString(3));
				json.put("likes", rs.getString(4));
				json.put("dislikes", rs.getString(5));
				json.put("share", rs.getString(6));
				jsonArr.add(json);
			}
			
			rs.close();
			s.close();
		}
		catch(Exception e)
		{
			System.out.println(e.getMessage());
		}
		mysqlconn.closeConn(conn);
		response.setContentType("application/json");
		response.getWriter().write(jsonArr.toString());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		
		PrintWriter out = response.getWriter();
		response.setContentType("text/plain");
		out.println("<h1>Servlet File Upload Example using Commons File Upload</h1>");
		out.println();

		DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
		/*
		 * Set the size threshold, above which content will be stored on disk.
		 */
		fileItemFactory.setSizeThreshold(1 * 1024 * 1024); // 1 MB
		/*
		 * Set the temporary directory to store the uploaded files of size above
		 * threshold.
		 */
		fileItemFactory.setRepository(tmpDir);

		ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
		try {
			/*
			 * Parse the request
			 */
			String fieldname = "";
			String filename = "";
			
			List items = uploadHandler.parseRequest(request);
			Iterator itr = items.iterator();
			while (itr.hasNext()) {
				FileItem item = (FileItem) itr.next();
				/*
				 * Handle Form Fields.
				 */
				if (item.isFormField()) {
					fieldname = item.getFieldName();
					if (fieldname.equals("name")) {
						filename = item.getString();
					} else if (fieldname.equals("token")) {
						userid = item.getString();
					}
				}
				else if (!item.isFormField()) {
/*					Date d = new Date();
					SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
					filename = sdf.format(d);*/
					File file = new File(DESTINATION_DIR_PATH, filename + ".png");
					item.write(file);

					Connection conn = mysqlconn.getConn();
					if (conn != null) {
						try {
							Statement s = conn.createStatement();
							String sql = "insert into photos(photoname,owner) values(";
							sql = sql + filename + ", " + userid + ");";
							s.execute(sql);
							s.close();
						} catch (Exception e) {
							System.out.println(e.getMessage());
						}
					}
					mysqlconn.closeConn(conn);
				}
			}
			out.close();
		} catch (FileUploadException ex) {
			System.out.println(ex.getMessage());
		} catch (Exception ex) {
			System.out.println(ex.getMessage());
		}
	}

	/**
	 * @see HttpServlet#doPut(HttpServletRequest, HttpServletResponse)
	 */
	protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		userid = request.getParameter("token");
		outfitid = request.getParameter("id");
		share = request.getParameter("share");
		like = Integer.parseInt(request.getParameter("like"));
		if (share != null)
		{
			sqlstr = "update photos set share = " + share + " where photoid = " + outfitid + " and owner = " + userid;
		} else if (like == 0 || like == 1)
		{
			if (like == 1)
			{
				sqlstr = "update photos set likes = likes + 1 where photoid = " + outfitid;
			}
			else
			{
				sqlstr = "update photos set dislikes = dislikes + 1 where photoid = " + outfitid;
			}
		}
		
		mysqlconn sqlconn = new mysqlconn();
		Connection conn = sqlconn.getConn();
		try {
			Statement s = conn.createStatement();
			int i = s.executeUpdate(sqlstr);
			if (i == 0)
				System.out.println(sqlstr + "<br>succeed!");
			else
				System.out.println(sqlstr + "<br>failed!");
			s.close();
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
		sqlconn.closeConn(conn);
	}

}
